<template>
  <div style="height: 400px;width: 400px;text-align: right">
    <el-button class="xml-download-button" type="primary" @click="downloadSVG">Download SVG</el-button>
    <div style="height: 400px;width: 400px" ref="mermaidChart">

    </div>
  </div>
</template>

<script>
import mermaid from 'mermaid';

export default {
  props: {
    chart: {
      type: String,
      required: true
    }
  },
  mounted() {

  },
  methods: {
    renderMermaid() {
      mermaid.initialize({
        startOnLoad: false,
        look:'handDrawn',
        theme: 'forest',        // 主题，可以是 'default', 'forest', 'dark', 'neutral'
      });
      mermaid.render('mermaidChart', this.chart, (svgCode) => {
        this.$refs.mermaidChart.innerHTML = svgCode;
      });
      this.$nextTick(() => {
        const svg = this.$refs.mermaidChart.querySelector('svg');
        if (svg) {
          var viewBox = svg.getAttribute('viewBox');
          var strings = viewBox.split(" ");
          var scale = '-20  -20' + ' '+(strings[2]*1.5)+' '+(strings[3]*1.5);
          console.log(scale)
          svg.setAttribute('width', '100%');
          svg.setAttribute('height', '100%');
          svg.setAttribute('style', '');
          svg.setAttribute('viewBox', scale);
        }
      });
    },
    downloadSVG() {
      const svgElement = this.$refs.mermaidChart.querySelector('svg');
      if (svgElement) {
        const serializer = new XMLSerializer();
        const source = serializer.serializeToString(svgElement);
        const svgBlob = new Blob([source], { type: 'image/svg+xml;charset=utf-8' });
        const url = URL.createObjectURL(svgBlob);
        const downloadLink = document.createElement('a');
        downloadLink.href = url;
        downloadLink.download = 'mermaid_chart.svg';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        URL.revokeObjectURL(url);
      }
    }
  },
  watch: {
    chart() {
      this.renderMermaid();
    }
  }
};
</script>
<style>
.xml-download-button{
  position: absolute;
  margin-top: 10px;
}
</style>
